package com.javasea.websocket.service;

import com.javasea.websocket.entity.JsonMessage;
import com.javasea.websocket.entity.SessionUser;
import com.javasea.websocket.utils.JacksonUtils;
import com.javasea.websocket.utils.SpringContextHolder;
import com.javasea.websocket.utils.WsBroadcastUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.naming.AuthenticationException;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Date;


/**
 * @Author: Ethan_Fung
 * @Description:
 * @Date: 2019/10/28 11:01
 * @Version: 1.0
 **/
@Slf4j
@Component
@ServerEndpoint(value = "/websocket/{userid}/{tenantId}/{userName}")
public class WebSuckit {

    /**
     * userId-UserSession
     */
//    private static Map<String, UserSession> sessionMap = new ConcurrentHashMap<String, UserSession>();

//    private LoginUserCache loginUserCache;

    private String userId;
    private String tenantId;
    private String userName;

    @OnOpen
    public void onOpen(Session session) throws Exception {
        this.userId = session.getPathParameters().get("userid");
        this.tenantId = session.getPathParameters().get("tenantId");
        this.userName = session.getPathParameters().get("userName");
        log.info("websocket 链接开启: " + this.userId + ":" + this.userName);
        if (null != this.userId && !this.userId.isEmpty()) {
            //添加session
            LoginUserCache.put(userId, new SessionUser(session, userId, userName, tenantId));
            WsBroadcastUtil.broadcastNotifications(session, new JsonMessage(Action.LINK_OPEN.name(), "链接开启", LoginUserCache.size() + "", "", "你好，欢迎连接WebSocket！"));
            Action.LINK_OPEN.getAction().action(null, session);
        } else {
            throw new AuthenticationException("请登录");
        }
    }

    @OnClose
    public void onClose() {
        try {
            SessionUser userSession = LoginUserCache.get(this.userId);
            log.info("websocket 链接关闭, userId: " + userSession.getUserId());
            WsBroadcastUtil.broadcastNotifications(this.userId, new JsonMessage(Action.LINK_CLOSE.name(), "链接关闭", null, "", "链接关闭"));

            LoginUserCache.remove(this.userId);
            log.info("用户：" + this.userName + ">>>已退出");
            Action.LINK_CLOSE.getAction().action(null, userSession.getSession());
            this.userId = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            log.info("websocket 接受到消息：" + message);
            JsonMessage jsonMessage = JacksonUtils.json2pojo(message,JsonMessage.class);
            String action = jsonMessage.getName();
            Action.valueOf(action).getAction().action(message, session);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        try {
            log.error("websocket 发生错误", error);
            SessionUser userSession = LoginUserCache.get(this.userId);
//        broadcastNotifications(this.userId, new JsonMessage("HEART_CHECK", null, "心跳"));

            LoginUserCache.remove(this.userId);
            log.info("用户：" + this.userName + ">>>已退出");
            //通知所有人
            Action.LINK_CLOSE.getAction().action(null, userSession.getSession());
            this.userId = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
